
package com.zjxd.business.web.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.zjxd.business.web.code.ApiResultCode;
import com.zjxd.business.web.code.MapCode;
import com.zjxd.business.web.common.ApiResult;
import com.zjxd.business.web.utils.MapUtils;
import com.zjxd.business.web.utils.RSAUtils;
import com.zjxd.business.web.utils.Utils;

/**
 * 参数验证拦截器
 * 
 * @author QIk
 */
public class ParameterValidateInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		String sign = request.getParameter("sign");
		if (StringUtil.isEmpty(sign)) {
			renderJson(response, ApiResult.fail(ApiResultCode.parameter_error_code));
			return false;
		}
		Map<String, String[]> parameter = new HashMap<String, String[]>(request.getParameterMap());
		parameter.remove("sign");// 密文不进行验证
		try {
			StringBuffer data = new StringBuffer();
			List<Map.Entry<String, String[]>> infos = Utils.sortMap2(parameter);
			for (final Map.Entry<String, String[]> s : infos) {
				data.append(s.getValue()[0]).append(",");
			}
			if (!RSAUtils.verify(data.toString(), sign, MapUtils.get(MapCode.PUBLIC_KEY_STR_NAME).toString())) {
				renderJson(response, ApiResult.fail(ApiResultCode.parameter_error_code));
				return false;
			}
		} catch (Exception e) {
			renderJson(response, ApiResult.fail(ApiResultCode.parameter_error_code));
			return false;
		}
		return true;
	}

	public void renderJson(HttpServletResponse response, ApiResult result) throws IOException {

		PrintWriter writer = null;
		response.setHeader("Content-type", "text/html;charset=UTF-8");// 编码格式
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		writer = response.getWriter();
		writer.write(JSONObject.toJSONString(result));
		writer.flush();
		writer.close();
	}
}
